<template>
  <el-dialog
    :model-value="modelValue"
    title="文章修改"
    width="800px"
    :close-on-click-modal="false"
    :before-close="handleClose"
  >
    <el-form ref="myForm" :model="formData" :rules="rules" label-width="100px">
      <el-row>
        <el-col :md="14" :sm="24">
          <el-form-item label="标题" prop="title" maxlength="64">
            <el-input v-model.trim="formData.title" type="tel" />
          </el-form-item>
        </el-col>
        <el-col :md="10" :sm="12">
          <el-form-item label="发布时间" prop="publish_time">
            <el-date-picker
              v-model="formData.publish_time"
              type="datetime"
              placeholder="选择日期"
              value-format="YYYY-MM-DD HH:mm:ss"
            >
            </el-date-picker>
            <span style="color: rgb(159, 159, 159); margin-left: 20px"
              >不填写时默认为系统当前时间</span
            >
          </el-form-item>
        </el-col>
        <el-col :md="12">
          <el-form-item label="栏目" prop="t_nav_fk">
            <cat-options v-model="formData.t_nav_fk" :empty="false" />
          </el-form-item>
        </el-col>
        <el-col :md="24">
          <el-form-item label="内容" prop="content">
            <div>
              <toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editorRef"
                :defaultConfig="toolbarConfig"
              />
              <editor
                style="height: 500px; overflow-y: hidden"
                v-model="formData.content"
                :defaultConfig="editorConfig"
                @onCreated="handleCreated"
              />
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-button @click="handleClose" type="danger">关闭</el-button>
        <el-button @click="handleReset(updateData)">重置</el-button>
        <el-button type="primary" @click="handleUpdate(myForm)">修改</el-button>
      </el-row>
    </el-form>
    <dialog-progress :model-value="progressNum"></dialog-progress>
  </el-dialog>
</template>

<script lang="ts" setup>
// 引入 css
import "@wangeditor/editor/dist/css/style.css";
// 引入组件
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
// 引入类型定义
import { IEditorConfig, IToolbarConfig } from "@wangeditor/editor";
import DialogProgress from "@/components/public/dialog-progress";

import CatOptions from "./cat-options.vue";
import type { FormInstance, FormRules } from "element-plus";
import { defineProps, defineEmits, shallowRef, onBeforeUnmount } from "vue";
import setup from "@/util/update";
import setupUpload from "@/util/upload";

const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true,
    default: false,
  },
  updateData: {
    type: Object,
    required: true,
  },
});

const emits = defineEmits(["close"]);

// 富文本配置项
const editorConfig: Partial<IEditorConfig> = {
  placeholder: "请填写内容",
  MENU_CONF: {},
  hoverbarKeys: {
    attachment: {
      menuKeys: ["downloadAttachment"], // “下载附件”菜单
    },
  },
};

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 菜单栏配置，附件上传放在第22个位置
const toolbarConfig: Partial<IToolbarConfig> = {
    insertKeys: {
      index: 22, // 自定义插入的位置
      keys: ["uploadAttachment"], // “上传附件”菜单
    },
};

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = (editor) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
  // 打印所有可配置的菜单项
  // console.log(editorRef.value.getAllMenuKeys());
};

// 富文本校验规则，需要使用wangeditor提供的API，获取内容是否为空
const checkContent = (rule: any, value: any, callback: any) => {
  if (!value || editorRef.value.getText().trim() === "") {
    callback(new Error("请输入内容"));
  } else {
    callback();
  }
};

const { rules, myForm, formData, handleReset, handleClose, handleUpdate } =
  setup(
    "article",
    props,
    emits,
    {
      title: [{ required: true, message: "请输入标题", trigger: "blur" }],
      t_nav_fk: [{ required: true, message: "请选择栏目", trigger: "blur" }],
      content: [
        {
          required: true,
          validator: checkContent,
          message: "请填写内容",
          trigger: "change",
        },
      ],
    },
    "/article/queryRow"
  );

  const {asyncRequest,progressNum} = setupUpload();

if (editorConfig.MENU_CONF) {
  console.log("ybde");

  // 上传图片配置
  editorConfig.MENU_CONF["uploadImage"] = {
    // 单个文件的最大体积限制，默认为 2M
    maxFileSize: 3 * 1024 * 1024, // 3M

    // 自定上传图片：上传到七牛云
    customUpload(file: any, insertFn: any) {
      asyncRequest({ file }).then((res) => {
        insertFn(res.file_path, res.file_name);
      });
    },
  };

  // 上传视频配置
  editorConfig.MENU_CONF["uploadVideo"] = {
    // 单个文件的最大体积限制，默认为 10M
    maxFileSize: 20 * 1024 * 1024, // 20M

    // 自定上传视频：上传到七牛云
    customUpload(file: any, insertFn: any) {
      asyncRequest({ file }).then((res) => {
        insertFn(res.file_path);
      });
    },
  };

  // 上传附件配置
  editorConfig.MENU_CONF["uploadAttachment"] = {
    maxFileSize: 10 * 1024 * 1024, // 10M

    // 自定上传附件：上传到七牛云
    customUpload(file: any, insertFn: any) {
      asyncRequest({ file }).then((res) => {
        console.log("res = ", res);
        insertFn(res.file_name, res.file_path);
      });
    },
  };
}
</script>

<style scoped>
</style>
